package com.ssyc.gsk_teacher.activity;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.PopLvAdapter;
import com.ssyc.gsk_teacher.adapter.TeamRvAdapter;
import com.ssyc.gsk_teacher.bean.CommitResultInfo;
import com.ssyc.gsk_teacher.bean.TeamInfo;
import com.ssyc.gsk_teacher.bean.TeamPassData;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * 修改小组信息界面
 * Created by Administrator on 2018/6/27 0027.
 */

public class TeacherEditTeamActivity extends BaseActivity implements View.OnClickListener {
    //返回
    private ImageView ivBack;

    //标题
    private TextView tvTitle;

    //保存按钮
    private Button btSave;

    private TextView tvTeamName;
    private TextView tvTeamSlogan;
    private TextView tvTeamTarget;
    private TextView tvTeamMusic;
    private CircleImageView ivTeamHeadimg;

    private RelativeLayout rlTeamIcon;
    private RelativeLayout rlTeamName;
    private RelativeLayout rlTeamSlogan;
    private RelativeLayout rlTeamTarget;
    private RelativeLayout rlTeamMusic;

    //跳转的请求码
    public static final int TEAMNAME = 0x110;
    public static final int TEAMSLOGAN = 0x120;
    public static final int TEAMTARGET = 0x130;
    public static final int TEAMMUSIC = 0x140;

    //用于记录弹框小组的初始值
    private int positon = 0;
    //弹框的适配器
    private PopLvAdapter popLvAdapter;

    //记录小组姓名
    public String teamName, oldTeamName;

    //记录小组口号
    public String teamSlogan, oldTeamSlogan;

    //记录小组口号
    public String teamTarget, oldTeamTarget;

    //记录小组音乐的索引
    public String musicIndex, oldMusicIndex;

    //小组的数据对象
    private TeamInfo.TeamsinfoBean info;

    //封装携带小组名称集合,口号集合,目标集合,小组音乐集合的数据对象
    private TeamPassData teamPassData;

    //小组的头像
    private int[] res = {R.drawable.teacher_team1, R.drawable.teacher_team2, R.drawable.teacher_team3, R.drawable.teacher_team4, R.drawable.teacher_team5,
            R.drawable.teacher_team6, R.drawable.teacher_team7, R.drawable.teacher_team8, R.drawable.teacher_team9, R.drawable.teacher_team10};

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_edit_team;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //设置初始化状态
        initState();
    }

    /**
     * 初始化Viiew
     */
    public void initView() {
        ivTeamHeadimg = findViewById(R.id.iv_team_headimg);
        tvTeamName = findViewById(R.id.tv_team_name);
        rlTeamName = findViewById(R.id.rl_team_name);
        rlTeamName.setOnClickListener(this);
        tvTeamSlogan = findViewById(R.id.tv_team_slogan);
        rlTeamSlogan = findViewById(R.id.rl_team_slogan);
        rlTeamSlogan.setOnClickListener(this);
        tvTeamTarget = findViewById(R.id.tv_team_target);
        rlTeamTarget = findViewById(R.id.rl_team_target);
        rlTeamTarget.setOnClickListener(this);
        tvTeamMusic = findViewById(R.id.tv_team_music);
        rlTeamMusic = findViewById(R.id.rl_team_music);
        rlTeamMusic.setOnClickListener(this);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        btSave = findViewById(R.id.bt_commit);
        btSave.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_title);
    }

    /**
     * 设置初始化状态
     */
    private void initState() {
        info = (TeamInfo.TeamsinfoBean) getIntent().getSerializableExtra("teaminfo");
        teamPassData = (TeamPassData) getIntent().getSerializableExtra("teampassdata");
        if (null != info) {
            //设置标题
            oldTeamName = info.getName();
            teamName = info.getName();
            tvTitle.setText(info.getName());
            //设置小组头像
            ivTeamHeadimg.setImageResource(res[info.getIcon() - 1]);
            //设置小组名称
            teamName = info.getName();
            oldTeamName = info.getName();
            tvTeamName.setText(info.getName());
            //设置小组目标
            teamSlogan = info.getSlogan();
            oldTeamSlogan = info.getSlogan();
            tvTeamSlogan.setText(info.getSlogan());
            //设置小组目标
            teamTarget = info.getAim();
            oldTeamTarget = info.getAim();
            tvTeamTarget.setText(info.getAim());
            //设置小组音乐
            musicIndex = info.getMusic();
            oldMusicIndex = info.getMusic();
            tvTeamMusic.setText(info.getMusic());
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {

        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.rl_team_name) {
            //小组名称
            choosePop(0);
        } else if (id == R.id.rl_team_slogan) {
            //小组口号
            choosePop(1);
        } else if (id == R.id.rl_team_target) {
            //小组目标
            choosePop(2);
        } else if (id == R.id.rl_team_music) {
            //小组音乐,跳转到选择小组音乐的界面
            chooseTeamMusicAction();
        } else if (id == R.id.bt_commit) {
            //保存
            doJudgeAllCommit();
        }
    }

    /**
     * 判断是否有修改,然后上传服务器
     */
    private void doJudgeAllCommit() {
        if (hasUpdate()) {
            //修改过,重新上传学生信息
            doUpdateTeaminfo();
        } else {
            SnackbarUtil.ShortSnackbar(llBaseMain, "未修改任何信息,不需要上传", Snackbar.LENGTH_SHORT).show();
        }
    }


    /**
     * 上传修改的小组信息
     */
    private void doUpdateTeaminfo() {
        CustomDialogManager.show(this, "修改中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "10");
        map.put("c", AccountUtils.getAccount(TeacherEditTeamActivity.this));
        map.put("id", info.getId() + "");
        map.put("icon", info.getIcon() + "");
        map.put("name", teamName);
        map.put("music", musicIndex);
        map.put("slogan", teamSlogan);
        map.put("aim", teamTarget);
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.UPDATETEAMINO, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("服务器异常,修改失败", false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    CommitResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, CommitResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info) {
                        if ("1".equals(info.getStatus())) {
                            //返回成功
                            UiUtils.Toast("修改成功", false);
                            //通知TeacherStudentFileActivity页面刷新
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(TeamRvAdapter.UPDATAPAGEDATA);
                            EventBus.getDefault().post(busInfo);
                            //通知页面刷新
                            finish();
                        } else if ("-1".equals(info.getStatus())) {
                            UiUtils.Toast("修改失败,服务器处理异常", false);
                        } else if ("0".equals(info.getStatus())) {
                            UiUtils.Toast("修改失败,该小组不存在", false);
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }

    /**
     * 判断是否修改了学生信息的方法
     *
     * @return
     */
    private boolean hasUpdate() {
        boolean res = false;
        //修改头像
        if ((!TextUtils.isEmpty(teamName) && !TextUtils.isEmpty(oldTeamName) && !oldTeamName.equals(teamName)) ||
                (!TextUtils.isEmpty(teamSlogan) && !TextUtils.isEmpty(oldTeamSlogan) && !teamSlogan.equals(oldTeamSlogan)) ||
                (!TextUtils.isEmpty(teamTarget) && !TextUtils.isEmpty(oldTeamTarget) && !oldTeamTarget.equals(teamTarget)) ||
                (!TextUtils.isEmpty(musicIndex) && !TextUtils.isEmpty(oldMusicIndex) && !oldMusicIndex.equals(musicIndex))) {
            res = true;
        }
        return res;
    }

    /**
     * 跳转到选择小组音乐的界面
     */
    private void chooseTeamMusicAction() {
        Intent intent = new Intent(this, TeacherChooseMusicAcitivity.class);
        startActivityForResult(intent, TEAMMUSIC);
    }


    /**
     * 选择头像后的回调处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            if (requestCode == TEAMNAME && resultCode == TeacherUpdataTeamInfoActivity.TEAMNAME) {
                //名称的回调
                teamName = data.getStringExtra("data");
                tvTeamName.setText(data.getStringExtra("data"));
            } else if (requestCode == TEAMSLOGAN && resultCode == TeacherUpdataTeamInfoActivity.TEAMSLOGAN) {
                //口号的回调
                teamSlogan = data.getStringExtra("data");
                tvTeamSlogan.setText(data.getStringExtra("data"));
            } else if (requestCode == TEAMTARGET && resultCode == TeacherUpdataTeamInfoActivity.TEAMTARGET) {
                //目标的回调
                teamTarget = data.getStringExtra("data");
                tvTeamTarget.setText(data.getStringExtra("data"));
            } else if (requestCode == TEAMMUSIC && resultCode == TeacherChooseMusicAcitivity.TEAMMUSIC) {
                //选择音乐后的回调
                musicIndex = data.getStringExtra("index");
                tvTeamMusic.setText(musicIndex + "");
            }
        }
    }


    /**
     * 弹框编辑小组的相关信息
     */
    private void choosePop(final int type) {
        final List<String> contents = new ArrayList<>();
        if (type == 0) {
            contents.add("智者队");
            contents.add("勇者队");
            contents.add("欢乐队");
            contents.add("博爱队");
            contents.add("自定义");
        } else if (type == 1) {
            contents.add("团结一心,其利断金");
            contents.add("披荆斩棘,剑指第一");
            contents.add("激情飞扬,智慧无限");
            contents.add("力争上游,永不言败");
            contents.add("自定义");
        } else if (type == 2) {
            contents.add("boss是我们的!");
            contents.add("第一被我们承包啦!");
            contents.add("快乐比拼,开心学习!");
            contents.add("我们的目标是:赢!");
            contents.add("自定义");
        }

        //弹框
        PopUpManager.showPop(this, R.layout.teacher_pop_item_common, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //标题
                TextView tvTitle = view.findViewById(R.id.tv_title);
                //列表
                ListView lv = view.findViewById(R.id.lv);
                //取消
                TextView tvCancel = view.findViewById(R.id.tv_cancel);

                if (type == 0) {
                    tvTitle.setText("小组名称");
                } else if (type == 1) {
                    tvTitle.setText("小组口号");
                } else if (type == 2) {
                    tvTitle.setText("小组目标");
                }

                //设置列表数据
                popLvAdapter = new PopLvAdapter(TeacherEditTeamActivity.this, contents,
                        R.layout.teacher_lv_item_pop_common);
                lv.setAdapter(popLvAdapter);

                //条目点击事件
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

                        if ("自定义".equals(contents.get(pos))) {
                            Intent intent = new Intent(TeacherEditTeamActivity.this, TeacherUpdataTeamInfoActivity.class);
                            if (type == 0) {
                                // 名称
                                intent.putExtra("teaminfo", "小组名称");
                                intent.putExtra("type", TEAMNAME);
                                startActivityForResult(intent, TEAMNAME);
                            } else if (type == 1) {
                                //口号
                                intent.putExtra("teaminfo", "小组口号");
                                intent.putExtra("type", TEAMSLOGAN);
                                startActivityForResult(intent, TEAMSLOGAN);
                            } else if (type == 2) {
                                //目标
                                intent.putExtra("teaminfo", "小组目标");
                                intent.putExtra("type", TEAMTARGET);
                                startActivityForResult(intent, TEAMTARGET);
                            }
                            PopUpManager.dismiss();
                        } else {
                            if (type == 0) {
                                // 名称,这里还需要处理名称是否已经被使用过的比较,因为名称不能重复
                                //获取页面传递过来的所有小组的名称集合,然后判断该集合中是否包含选择的名称
                                List<String> teamNames = teamPassData.teamNames;
                                if (teamNames.contains(contents.get(pos))) {
                                    //名称被使用过
                                    UiUtils.Toast("该名称已经被使用了", false);
                                } else {
                                    teamName = contents.get(pos);
                                    tvTeamName.setText(contents.get(pos));
                                    PopUpManager.dismiss();
                                }

                            } else if (type == 1) {
                                //口号
                                List<String> teamSlogans = teamPassData.teamSlogans;
                                if (teamSlogans.contains(contents.get(pos))) {
                                    //名称被使用过
                                    UiUtils.Toast("该口号已经被使用了", false);
                                } else {
                                    teamSlogan = contents.get(pos);
                                    tvTeamSlogan.setText(contents.get(pos));
                                    PopUpManager.dismiss();
                                }
                            } else if (type == 2) {
                                //目标
                                List<String> teamAims = teamPassData.teamAims;
                                if (teamAims.contains(contents.get(pos))) {
                                    //名称被使用过
                                    UiUtils.Toast("该目标已经被使用了", false);
                                } else {
                                    teamTarget = contents.get(pos);
                                    tvTeamTarget.setText(contents.get(pos));
                                    PopUpManager.dismiss();
                                }
                            }
                        }
                    }
                });

                //取消的点击事件
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

}
